<!--
 * @Description: 运输地图
 * @Autor: wangwangwang
 * @Date: 2021-05-11 11:18:06
 * @LastEditors: wangwangwang
 * @LastEditTime: 2021-08-02 16:12:40
-->
<template>
  <div class="main-container">
    <el-container>
      <el-main style="padding:10px 20px; 0">
        <div>
          <div class="search">
            <span style="margin-right: 24px;">
              <span style="margin-right: 12px;">站点</span>
              <el-select v-model="searchParams.stationId" style="width: 220px;" placeholder="请选择">
                <el-option v-for="(item, index) in stationList" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </span>
            <span style="display: inline-block;margin-bottom: 10px;">
              <span style="margin-right: 12px;">工程名称</span>
              <el-input v-model="searchParams.engineeringName" style="width: 220px;" placeholder="请输入" @keyup.enter.native="gettableData()" />
            </span>
            <span style="margin-left: 24px;">
              <span style="margin-right: 12px;">订单号</span>
              <el-input v-model="searchParams.orderNo" style="width: 150px;" placeholder="请输入" @keyup.enter.native="gettableData()" />
            </span>
            <span style="margin-left: 24px;">
              <span style="margin-right: 12px;">车牌号</span>
              <el-input v-model="searchParams.carNo" style="width: 150px;" placeholder="请输入" @keyup.enter.native="gettableData()" />
            </span>
            <el-button icon="el-icon-search" size="medium" class="bottom_all but1" @click="gettableDataMap(),resetTimer()">查 询</el-button>
            <el-button size="medium" class="bottom_all_two" style="margin-left:12px;" @click="handleReset(),resetTimer()">重 置</el-button>
            <el-button size="medium" class="bottom_all_two" style="margin-left:12px;" @click="XinRuanGPS()">星软GPS</el-button>
          </div>
        </div>
        <div style="height:calc(100vh - 266px);padding:10px; 0">
          <el-amap ref="amapManager" vid="amap" :center="mapCenter" :zoom="zoom" class="amap-demo">
            <el-amap-marker v-for="(item, index) in markers" :key="index+100" :position="item.position" :vid="item.vid" :content="setMarkerContent(item)" :events="item.events"></el-amap-marker>
            <el-amap-circle v-for="(item,index) in circles" :key="index" :center="item.center" :radius="item.radius" :fill-opacity="item.fillOpacity" :bubble="true" :events="item.events"></el-amap-circle>
            <!-- <el-amap-polyline v-for="(line, index) in lines" :key="index+1000" :path="line.path" :stroke-color="line.strokeColor" :stroke-style="line.strokeStyle" :stroke-opacity="line.strokeOpacity"></el-amap-polyline> -->
          </el-amap>
        </div>
      </el-main>
    </el-container>
    <div style="margin:0 20px;">
      <div>
        <el-table border :header-cell-style="{ background: '#f3f6f9' }" :data="dataSource1">
          <el-table-column prop="engineeringName" label="工程名称"></el-table-column>
          <el-table-column prop="orderNo" label="订单号"></el-table-column>
          <el-table-column prop="productName" label="产品名称"></el-table-column>
          <el-table-column prop="transNum" label="运输量（方）"></el-table-column>
          <el-table-column prop="discloseDistance" label="合同运距(千米)"></el-table-column>
          <el-table-column prop="distance" label="智能运距(千米)"></el-table-column>
          <el-table-column prop="driverName" label="运输司机"></el-table-column>
          <el-table-column prop="driverPhone" label="电话"></el-table-column>
          <el-table-column label="浇筑部位" align="center" prop="structuralParts"></el-table-column>
          <el-table-column label="浇筑方式" align="center" prop="pouringMethod">
            <template slot-scope="scope">
              {{scope.row.pouringMethod?JSON.parse(scope.row.pouringMethod).map(item => item.name).join(','):''}}
            </template>
          </el-table-column>
          <el-table-column label="生产时间" align="center" prop="proTime"></el-table-column>
          <el-table-column label="签收时间" align="center" prop="affirmTime"></el-table-column>
          <el-table-column label="累计车数" align="center" prop="cumulativeTrains"></el-table-column>
          <el-table-column label="累计方量" align="center" prop="faceValue"></el-table-column>
          <el-table-column label="操作" fixed="right" width="130">
            <template slot-scope="scope">
              <el-button class="bottom_all" @click="showTransRecord(scope.row)">历史物流</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="padding:10px 0px">
        <el-table border :header-cell-style="{ background: '#f3f6f9' }" style="width:100%" :data="dataSource2">
          <el-table-column prop="engineeringName" label="工程名称"></el-table-column>
          <el-table-column prop="orderNum" label="累计订单数"></el-table-column>
          <el-table-column prop="logisticsNum" label="累计供应车次"></el-table-column>
          <el-table-column prop="signSum" label="累计供应量（方）"></el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog :visible.sync="historyVisible" width="1180px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">历史物流</span>
      <div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width: 100%" :data="historyList" tooltip-effect="dark" height="400">
          <el-table-column width="150" label="物流编号" align="center" prop="code"></el-table-column>
          <el-table-column label="工程名称" align="center" prop="engineeringName"></el-table-column>
          <el-table-column label="订单号" align="center" prop="orderNo"></el-table-column>
          <el-table-column label="产品名称" align="center" prop="productName"></el-table-column>
          <el-table-column label="车牌号" align="center" prop="carNo"></el-table-column>
          <el-table-column label="运输量（方）" align="center" prop="faceValue"></el-table-column>
          <el-table-column label="运输司机" align="center" prop="driverName"></el-table-column>
          <el-table-column label="电话" align="center" prop="driverPhone"></el-table-column>
          <el-table-column label="浇筑部位" align="center" prop="structuralParts"></el-table-column>
          <el-table-column label="浇筑方式" align="center" prop="pouringMethod">
            <template slot-scope="scope">
              {{JSON.parse(scope.row.pouringMethod).map(item => item.name).join(',')}}
            </template>
          </el-table-column>
          <el-table-column label="生产时间" align="center" prop="proTime"></el-table-column>
          <el-table-column label="签收时间" align="center" prop="affirmTime"></el-table-column>
          <el-table-column label="累计车数" align="center" prop="cumulativeTrains"></el-table-column>
          <el-table-column label="累计方量" align="center" prop="faceValue"></el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="130">
            <template slot-scope="scope">
              <el-button class="bottom_all" @click="showTrail(scope.row)">查看轨迹</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="historyVisible=false">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="mapVisible" width="1180px" :close-on-click-modal="false">
      <span slot="title" class="dialog-title">查看轨迹</span>
      <div style="height: 500px;">
        <el-amap ref="bmapManager" vid="bmap" :center="mapCenter" :zoom="zoom" class="amap-demo">
          <el-amap-polyline :path="linesPath" stroke-color="#FF33FF" stroke-style="solid" stroke-opacity="1"></el-amap-polyline>
        </el-amap>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="mapVisible=false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import {
  getCarInfo,
  QueryPageElectronicFence, getOrderInfoByEngineeringId, getLogisticsByCarNo, getCarPath, XingRuangetLists, getXinRuanPosition
} from "@/api/smart/schedul/j.js";
import { getUserInfo } from "@/utils/auth.js";
import { getUserAutList } from "@/api/common.js";

export default {
  mixins: [mixin],
  data() {
    return {
      UserInfo: '',
      searchParams: {
        stationId: '',
        engineeringName: '',
        orderNo: '',
        carNo: '',
      },
      principalName: '',
      currentWindow: {
        position: [104.045543, 30.53947],
        content: "",
        offset: [0, -20],
        visible: false,
        events: {},
      },
      searchOption: {
        city: "全国",
        citylimit: true,
      },
      markers: [],
      plugin: [],
      zoom: 14,
      mapCenter: [104.045543, 30.53947],
      /*表格数据*/
      /*表单页类型，0为无树状，1为有树状，有树状在el-main加上display:flex*/
      pagesType: 0,
      circles: [],//电子围栏
      lines: [],
      stationList: [],
      dataSource1: [],
      dataSource2: [],
      historyVisible: false,
      mapVisible: false,
      historyList: [],
      linesPath: [],
      timer: '',
    };
  },
  async created() {
    this.UserInfo = await getUserInfo();
    this.stationList = await getUserAutList(true);
    if (this.UserInfo.pointIds[0]) {
      this.searchParams.stationId = this.UserInfo.pointIds[0]
    } else {
      this.searchParams.stationId = this.stationList[0]?.id;
    }
    this.gettableDataMap();
  },
  methods: {
    showTransRecord (data) {
      getLogisticsByCarNo({carNo: data.carNo}).then(res => {
        if (res.code === 1001) {
          this.historyList = res.data;
          this.historyVisible = true;
        }
      })
    },
    showTrail (data) {
      getCarPath({code: data.code}).then(res => {
        if (res.code === 1001) {
          this.mapVisible = true;
          this.linesPath = res.data.map(item => [item.longitude, item.latitude])
        }
      })
    },
    setMarkerContent (data) {
      const imgUri = require('@/assets/guanChe.png');
      const content = `<div style="text-align:center;width:180px;font-size:13px;">
                        <div style="padding:0 14px; border:1px solid #000; border-radius: 5px;background:#fff;width:180px;">${data.data.carNo||''},${data.data.transNum||''},${data.data.label||''}</div>
                        <img src=${imgUri} />
                       </div>`;
      return content;
    },
    handleReset () {
      this.searchParams.orderNo = '';
      this.searchParams.carNo = '';
      this.searchParams.engineeringName = '';
      this.gettableDataMap();
    },
    XinRuanGPS () {
      if (this.searchParams.carNo) {
        getXinRuanPosition({carNo: this.searchParams.carNo}).then(res => {
          if (res.code === 1001) {
            if (res.data.length) {
              this.initMapCar(res.data)
              clearInterval(this.timer);
              return
            }
            this.$message.warning('未查询到车辆信息');
          }
        })
      } else {
        XingRuangetLists({}).then(res => {
          if (res.code === 1001) {
            if (res.data.length) {
              this.initMapCar(res.data);
              clearInterval(this.timer);
              return
            }
            this.$message.warning('未查询到车辆信息');
          }
        })
      }
    },
    initMapCar (dataSource) {
      this.markers = [];
      dataSource.forEach((item, index) => {
        const data = {
          vid: index,
          position: [item.longitude || 104.045543, item.latitude || 30.53947],
          data: item,
          events: {
            click: () => {
              this.$message.success(item.adress);
              this.dataSource2 = [];
            }
          }
        };
        this.markers.push(data);
      });
    },
    gettableDataMap() {
      let json1 = {
        isAssess: "5",
        page: 1,
        pageSize: 999,
      }
      QueryPageElectronicFence(json1).then((res) => {
        if (res.code == 1001) {
          this.circles = []
          res.data.data.forEach((e) => {
            if (e.longitude) {
              this.circles.push({
                center: [e.longitude, e.latitude],
                radius: e.distance,
                fillOpacity: 0.2,
                events: {
                  click: () => {
                    getOrderInfoByEngineeringId({engineeringId: e.id,engineeringName: e.name}).then(res => {
                      if (res.code === 1001) {
                        this.dataSource2 = [res.data];
                      }
                    })
                  }
                }
              })
            }
          })
        }
      })
      let obj = {
        orderNo: this.searchParams.orderNo,
        carNo: this.searchParams.carNo,
        engineeringName: this.searchParams.engineeringName,
        stationId: this.searchParams.stationId,
        transportType: 'return_no',
      }
      /**
       * @Description: 获取车辆数据
       * @param {*}
       * @Author: wangwangwang
       */
      getCarInfo(obj).then((res) => {
        if (res.code == 1001) {
          if (res.data) {
            this.markers = [];
            const newArry = [];
            res.data.forEach(item => {
              const index = newArry.findIndex(items => items.carNo === item.carNo)
              if (index !== -1) {
                const oldTime = new Date(newArry[index].createTime).getTime();
                const newTime = new Date(item.createTime).getTime();
                if (newTime > oldTime) {
                  newArry.splice(index, 1, item);
                }
              } else {
                newArry.push(item);
              }
            })
            newArry.forEach((item, index) => {
              const data = {
                vid: index,
                position: [item.longitude || 104.045543, item.latitude || 30.53947],
                data: item,
                events: {
                  click: () => {
                    if (item.dataStatus === 4) {
                      this.dataSource1 = [{carNo: item.carNo}];
                    } else {
                      this.dataSource1 = [item];
                    }
                  }
                }
              };
              this.markers.push(data);
            });
            /**
             * @Description: 设置mapCenter
             * @param {*}
             * @Author: wangwangwang
             */     
            if (this.searchParams.carNo) {
              this.mapCenter = [newArry[0].longitude, newArry[0].latitude];
            } else {
              const station = this.stationList.find(item => item.id === this.searchParams.stationId);
              this.mapCenter = [station.longitude, station.dimensionality];
            }
          }
        }
      });
    },
    initArry (list, field) {
      let obj = {};
      for(let i = 0; i<list.length; i++){
        for (let item in list[i]) {
          if(item==field){
            obj[list[i][item]] = {
              list: obj[list[i][field]]?obj[list[i][field]].list:[],
            };
          }
        }
        obj[list[i][field]].list.push(list[i])
      }
      let att = [];
      for(let item in obj){
        att.push({
          list: obj[item].list,
        })
      }
      return att
    },
    resetTimer () {
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        this.gettableDataMap();
      }, 60000)
    }
  },
  mounted () {
    clearInterval(this.timer);
    this.timer = setInterval(() => {
      this.gettableDataMap();
    }, 60000)
  }
};
</script>
<style lang="scss" scoped>
.main-container{
  background: #fff;
}
</style>